<template>
  <div class="user-recommendation">
    <!-- 页面头部 -->
    <div class="header">
      <h2>智能课程推荐系统</h2>
      <div class="controls">
        <el-select v-model="selectedStudent" placeholder="选择学生" @change="fetchStudentRecommendations" clearable>
          <el-option label="请选择学生" value=""></el-option>
          <el-option
              v-for="student in students"
              :key="student"
              :label="student"
              :value="student">
          </el-option>
        </el-select>
        <el-select v-model="selectedType" placeholder="推荐类型" @change="fetchRecommendationsByType" clearable>
          <el-option label="全部类型" value=""></el-option>
          <el-option
              v-for="type in recommendationTypes"
              :key="type"
              :label="getTypeLabel(type)"
              :value="type">
          </el-option>
        </el-select>
        <el-button type="primary" @click="refreshData" :loading="loading">
          <i class="el-icon-refresh"></i> 刷新数据
        </el-button>
      </div>
    </div>

    <!-- 热门课程推荐 -->
    <div class="popular-section" v-if="!selectedStudent && !selectedType">
      <h3><i class="el-icon-star-on"></i> 热门课程推荐</h3>
      <div class="popular-courses" v-loading="popularLoading">
        <!-- 将 v-for 修改为迭代 popularCourses.slice(0, 4) -->
        <div
            v-for="(course, index) in popularCourses.slice(0, 4)"
            :key="index"
            class="popular-course-card">
          <div class="course-rank">
            <span class="rank-number">{{ index + 1 }}</span>
          </div>
          <div class="course-info">
            <h4>{{ course.courseName }}</h4>
            <div class="course-stats">
              <el-tag type="warning" size="small">
                <i class="el-icon-trophy"></i> 平均分: {{ course.recommendationScore.toFixed(2) }}
              </el-tag>
              <el-tag type="info" size="small">
                <i class="el-icon-user"></i> 推荐人数: {{ course.rankOrder }}
              </el-tag>
            </div>
          </div>
          <div class="course-progress">
            <el-progress
                type="circle"
                :percentage="getValidScorePercentage(course.recommendationScore)"
                :width="60"
                :color="getScoreColor(course.recommendationScore)">
            </el-progress>
          </div>
        </div>
        <!-- 为热门课程添加无数据提示 -->
        <div v-if="!popularLoading && popularCourses.length === 0" class="no-data">
          <el-empty description="暂无热门推荐课程"></el-empty>
        </div>
      </div>
    </div>

    <!-- 个人推荐结果 -->
    <div class="recommendations-section" v-if="selectedStudent || selectedType">
      <h3>
        <i class="el-icon-magic-stick"></i>
        {{ selectedStudent ? `学生 ${selectedStudent} 的` : '' }}
        {{ selectedType ? `${getTypeLabel(selectedType)}` : '' }}
        推荐结果
      </h3>
      <div class="recommendations-grid" v-loading="loading">
        <!-- 将 v-for 修改为迭代 recommendations.slice(0, 4) -->
        <div
            v-for="(recommendation, index) in recommendations.slice(0, 4)"
            :key="recommendation.id"
            class="recommendation-card"
            :class="getRecommendationClass(index)">

          <div class="card-header">
            <div class="rank-badge">
              <!-- index + 1 仍然正确显示排名 -->
              <i :class="getRankIcon(index)"></i>
              排名 {{ index + 1 }}
            </div>
            <div class="recommendation-type">
              <el-tag :type="getTypeColor(recommendation.recommendationType)" size="small">
                {{ getTypeLabel(recommendation.recommendationType) }}
              </el-tag>
            </div>
          </div>

          <div class="course-content">
            <h4 class="course-title">{{ recommendation.courseName }}</h4>
            <div class="student-info" v-if="!selectedStudent">
              <span class="student-id">学生: {{ recommendation.studentId }}</span>
            </div>
          </div>

          <div class="score-section">
            <div class="score-display">
              <el-progress
                  type="dashboard"
                  :percentage="getValidScorePercentage(recommendation.recommendationScore)"
                  :color="getScoreColor(recommendation.recommendationScore)"
                  :width="100">
                <template #default="{ percentage }">
                  <span class="score-value">{{ recommendation.recommendationScore.toFixed(2) }}</span>
                  <div class="score-label">推荐分数</div>
                  <div class="score-max">(满分5.0)</div>
                </template>
              </el-progress>
            </div>
            <!-- 显示原始数据用于调试 -->
            <div class="debug-info" v-if="showDebug">
              <small>原始分数: {{ recommendation.recommendationScore }}</small><br>
              <small>计算百分比: {{ getValidScorePercentage(recommendation.recommendationScore) }}%</small>
            </div>
          </div>

          <div class="card-footer">
            <div class="rank-info">
              <el-tag size="mini" type="info">
                <i class="el-icon-sort"></i> 权重排序: {{ recommendation.rankOrder }}
              </el-tag>
            </div>
            <div class="update-time">
              更新: {{ formatTime(recommendation.lastUpdated) }}
            </div>
          </div>
        </div>
        <!-- 为个人推荐添加无数据提示 -->
        <div v-if="!loading && recommendations.length === 0" class="no-data">
          <el-empty description="暂无推荐数据"></el-empty>
        </div>
      </div>
    </div>

    <!-- 原来的无数据提示块移除 -->
    <!-- <div v-if="!loading && recommendations.length === 0" class="no-data">
      <el-empty description="暂无推荐数据"></el-empty>
    </div> -->


    <!-- 统计信息 -->
    <!-- 统计信息 v-if 条件调整为只要有数据就显示 -->
    <div class="stats-section" v-if="recommendations.length > 0 || popularCourses.length > 0 || loading || popularLoading">
      <h3><i class="el-icon-data-analysis"></i> 推荐统计</h3>
      <div class="stats-cards">
        <div class="stat-card">
          <div class="stat-icon">
            <i class="el-icon-user-solid"></i>
          </div>
          <div class="stat-content">
            <div class="stat-number">{{ students.length }}</div>
            <div class="stat-label">学生总数</div>
          </div>
        </div>
        <div class="stat-card">
          <div class="stat-icon">
            <i class="el-icon-menu"></i>
          </div>
          <div class="stat-content">
            <div class="stat-number">{{ recommendationTypes.length }}</div>
            <div class="stat-label">推荐算法</div>
          </div>
        </div>
        <div class="stat-card">
          <div class="stat-icon">
            <i class="el-icon-notebook-2"></i>
          </div>
          <div class="stat-content">
            <div class="stat-number">4</div>
            <div class="stat-label">推荐课程</div>
          </div>
        </div>
        <div class="stat-card">
          <div class="stat-icon">
            <i class="el-icon-time"></i>
          </div>
          <div class="stat-content">
            <div class="stat-number">{{ getCurrentTime() }}</div>
            <div class="stat-label">当前时间</div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'UserRecommendation',
  data() {
    return {
      recommendations: [],
      popularCourses: [],
      students: [],
      recommendationTypes: [],
      selectedStudent: '',
      selectedType: '',
      loading: false,
      popularLoading: false,
      mockLoading: false,
      showDebug: process.env.NODE_ENV === 'development' // 开发环境显示调试信息
    }
  },

  mounted() {
    this.init()
  },

  methods: {
    async init() {
      await this.fetchStudents()
      await this.fetchRecommendationTypes()
      // init时只获取热门课程，不获取个人推荐
      await this.fetchPopularCourses()
      // 确保 recommendations 初始为空，以便 v-if 正确判断
      this.recommendations = []
    },

    async fetchStudents() {
      try {
        // 开始加载前清空学生列表，防止残留数据
        this.students = []
        const response = await this.$request.post('/api/user-recommendation/students', {})
        if (response.success) {
          this.students = response.data
        } else {
          // 即使失败也清空
          this.students = []
          this.$message.error(response.message || '获取学生列表失败')
        }
      } catch (error) {
        console.error('获取学生列表失败:', error)
        // 即使失败也清空
        this.students = []
        this.$message.error('获取学生列表失败')
      }
    },

    async fetchRecommendationTypes() {
      try {
        // 开始加载前清空类型列表
        this.recommendationTypes = []
        const response = await this.$request.post('/api/user-recommendation/types', {})
        if (response.success) {
          this.recommendationTypes = response.data
        } else {
          // 即使失败也清空
          this.recommendationTypes = []
          this.$message.error(response.message || '获取推荐类型失败')
        }
      } catch (error) {
        console.error('获取推荐类型失败:', error)
        // 即使失败也清空
        this.recommendationTypes = []
        this.$message.error('获取推荐类型失败')
      }
    },

    async fetchPopularCourses() {
      this.popularLoading = true
      try {
        // 开始加载前清空热门课程列表
        this.popularCourses = []
        const response = await this.$request.post('/api/user-recommendation/popular-courses', {
          limit: 6
        })
        if (response.success) {
          this.popularCourses = response.data
        } else {
          // 即使失败也清空
          this.popularCourses = []
          this.$message.error(response.message || '获取热门课程失败')
        }
      } catch (error) {
        console.error('获取热门课程失败:', error)
        // 即使失败也清空
        this.popularCourses = []
        this.$message.error('获取热门课程失败')
      } finally {
        this.popularLoading = false
      }
    },

    async fetchStudentRecommendations() {
      // 清空推荐类型选择，确保逻辑清晰
      this.selectedType = ''

      if (!this.selectedStudent) {
        // 如果学生被清空，回到初始状态，显示热门课程
        this.recommendations = []
        this.fetchPopularCourses() // 重新加载热门课程
        return
      }

      this.loading = true
      this.recommendations = [] // 开始加载前清空当前推荐列表
      try {
        const response = await this.$request.post('/api/user-recommendation/by-student', {
          studentId: this.selectedStudent,
          limit: 10 // 可以调整此处的 limit，虽然前端只显示4个，但获取多一些可以在后端处理排序或备用
        })
        if (response.success) {
          this.recommendations = response.data
          console.log('获取到的学生推荐数据:', this.recommendations)
        } else {
          // 即使失败也清空
          this.recommendations = []
          this.$message.error(response.message || '获取学生推荐失败')
        }
      } catch (error) {
        console.error('获取学生推荐失败:', error)
        // 即使失败也清空
        this.recommendations = []
        this.$message.error('获取学生推荐失败')
      } finally {
        this.loading = false
      }
    },

    async fetchRecommendationsByType() {
      // 清空学生选择，确保逻辑清晰
      this.selectedStudent = ''

      if (!this.selectedType) {
        // 如果类型被清空，回到初始状态，显示热门课程
        this.recommendations = []
        this.fetchPopularCourses() // 重新加载热门课程
        return
      }

      this.loading = true
      this.recommendations = [] // 开始加载前清空当前推荐列表
      try {
        const response = await this.$request.post('/api/user-recommendation/by-type', {
          recommendationType: this.selectedType,
          limit: 10 // 可以调整此处的 limit
        })
        if (response.success) {
          this.recommendations = response.data
          console.log('获取到的类型推荐数据:', this.recommendations)
        } else {
          // 即使失败也清空
          this.recommendations = []
          this.$message.error(response.message || '获取类型推荐失败')
        }
      } catch (error) {
        console.error('获取类型推荐失败:', error)
        // 即使失败也清空
        this.recommendations = []
        this.$message.error('获取类型推荐失败')
      } finally {
        this.loading = false
      }
    },

    async generateMockData() {
      this.mockLoading = true
      try {
        const response = await this.$request.post('/api/user-recommendation/generate-mock-data', {
          operator: 'hoaixanghao',
          timestamp: new Date().toISOString()
        })
        if (response.success) {
          this.$message.success('推荐模拟数据生成成功')
          // 生成数据后，重新初始化所有列表
          await this.init()
          // 如果有选中的学生或类型，重新获取对应数据
          if (this.selectedStudent) {
            await this.fetchStudentRecommendations()
          } else if (this.selectedType) {
            await this.fetchRecommendationsByType()
          }
        } else {
          this.$message.error(response.message || '生成推荐模拟数据失败')
        }
      } catch (error) {
        console.error('生成推荐模拟数据失败:', error)
        this.$message.error('生成推荐模拟数据失败')
      } finally {
        this.mockLoading = false
      }
    },

    async refreshData() {
      // 重置选择状态
      this.selectedStudent = ''
      this.selectedType = ''
      // 清空当前的推荐和热门课程，显示加载状态
      this.recommendations = []
      this.popularCourses = []
      // 重新初始化所有数据（学生、类型、热门课程）
      await this.init()
      this.$message.success('数据刷新成功')
    },

    // 修复推荐分数百分比计算
    getValidScorePercentage(score) {
      if (score === null || score === undefined) {
        return 0
      }

      // 推荐分数满分为5.0，计算百分比
      let percentage = Math.round((score / 5.0) * 100)

      // 确保在0-100范围内
      return Math.max(0, Math.min(100, percentage))
    },

    getTypeLabel(type) {
      const typeMap = {
        'CF': '协同过滤',
        'CBF': '基于内容',
        'HYBRID': '混合推荐'
      }
      return typeMap[type] || type
    },

    getTypeColor(type) {
      const colorMap = {
        'CF': 'primary',
        'CBF': 'success',
        'HYBRID': 'warning'
      }
      return colorMap[type] || 'info'
    },

    getRecommendationClass(index) {
      const classes = ['first-recommendation', 'second-recommendation', 'third-recommendation']
      // 只对前三个应用特殊样式
      return classes[index] || ''
    },

    getRankIcon(index) {
      // 只对前三个应用特殊图标
      const icons = ['el-icon-trophy', 'el-icon-medal', 'el-icon-star-on']
      return icons[index] || 'el-icon-star-off'
    },

    getScoreColor(score) {
      if (score === null || score === undefined) return '#909399'; // Handle null/undefined scores
      if (score >= 4.5) return '#f56c6c'; // 红色
      if (score >= 4.0) return '#e6a23c'; // 橙色
      if (score >= 3.5) return '#409eff'; // 蓝色
      return '#67c23a'; // 绿色 (小于3.5)
    },


    // getUniqueCourseCount() {
    //   const uniqueCourses = new Set()
    //   // 统计当前显示的课程总数
    //   // 如果显示个人推荐，统计 recommendations 中的课程
    //   if(this.selectedStudent || this.selectedType) {
    //     this.recommendations.forEach(rec => uniqueCourses.add(rec.courseName))
    //   } else {
    //     // 如果显示热门课程，统计 popularCourses 中的课程
    //     this.popularCourses.forEach(course => uniqueCourses.add(course.courseName))
    //   }
    //   // 如果两个列表都为空 (比如刚加载或者无数据)，可以考虑是否要统计所有可能的课程，
    //   // 但通常只统计当前显示的列表更符合语境。
    //   // 如果需要统计所有已知的课程，可以在 fetchStudents 或 init 中获取一个完整的课程列表。
    //   // 当前逻辑只统计当前渲染出来的课程名。
    //   return uniqueCourses.size
    // },

    formatTime(timeStr) {
      if (!timeStr) return '未知'
      try {
        // 尝试解析ISO 8601格式或时间戳
        const date = new Date(timeStr);
        if (isNaN(date.getTime())) {
          return '时间格式错误';
        }
        return date.toLocaleString('zh-CN', {
          month: '2-digit',
          day: '2-digit',
          hour: '2-digit',
          minute: '2-digit'
        })
      } catch (error) {
        console.error("时间格式化错误:", error);
        return '时间格式错误'
      }
    },

    getCurrentTime() {
      return new Date().toLocaleTimeString('zh-CN', {
        hour: '2-digit',
        minute: '2-digit'
      })
    }
  }
}
</script>

<style scoped>
/* 样式保持不变 */
.user-recommendation {
  padding: 20px;
  background: #f5f7fa;
  min-height: 100vh;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
  padding: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.header h2 {
  margin: 0;
  color: #303133;
}

.controls {
  display: flex;
  gap: 15px;
  align-items: center;
}

/* 其余样式保持不变... */
.score-max {
  font-size: 10px;
  color: #c0c4cc;
  margin-top: 2px;
}

.debug-info {
  margin-top: 10px;
  color: #909399;
  font-size: 12px;
  text-align: center;
}

.user-recommendation {
  padding: 20px;
  background: #f5f7fa;
  min-height: 100vh;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
  padding: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.header h2 {
  margin: 0;
  color: #303133;
}

.controls {
  display: flex;
  gap: 15px;
  align-items: center;
}

/* 热门课程样式 */
.popular-section {
  margin-bottom: 30px;
}

.popular-section h3 {
  color: #303133;
  margin-bottom: 20px;
  font-size: 18px;
}

.popular-courses {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(350px, 1fr));
  gap: 20px;
}

.popular-course-card {
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  display: flex;
  align-items: center;
  gap: 15px;
  transition: all 0.3s ease;
}

.popular-course-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
}

.course-rank {
  flex-shrink: 0;
}

.rank-number {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  width: 40px;
  height: 40px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border-radius: 50%;
  font-weight: bold;
  font-size: 18px;
}

.course-info {
  flex: 1;
}

.course-info h4 {
  margin: 0 0 10px 0;
  color: #303133;
  font-size: 16px;
}

.course-stats {
  display: flex;
  gap: 10px;
}

.course-progress {
  flex-shrink: 0;
}

/* 推荐结果样式 */
.recommendations-section h3 {
  color: #303133;
  margin-bottom: 20px;
  font-size: 18px;
}

.recommendations-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 20px;
  margin-bottom: 30px; /* 确保下方统计信息有足够空间 */
}

.recommendation-card {
  background: white;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
  border-top: 4px solid #409eff;
}

.recommendation-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 30px rgba(0, 0, 0, 0.15);
}

.first-recommendation {
  border-top-color: #ffd700; /* 金色 */
}

.second-recommendation {
  border-top-color: #c0c0c0; /* 银色 */
}

.third-recommendation {
  border-top-color: #cd7f32; /* 青铜色 */
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.rank-badge {
  display: flex;
  align-items: center;
  gap: 5px;
  color: #606266;
  font-weight: bold;
}

.course-content {
  margin-bottom: 20px;
}

.course-title {
  margin: 0 0 10px 0;
  color: #303133;
  font-size: 18px;
}

.student-info {
  color: #909399;
  font-size: 14px;
}

.score-section {
  text-align: center;
  margin-bottom: 20px;
}

.score-value {
  display: block;
  font-size: 18px;
  font-weight: bold;
  color: #303133;
}

.score-label {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
}

.card-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 12px;
  color: #c0c4cc;
}

/* 统计信息样式 */
.stats-section h3 {
  color: #303133;
  margin-bottom: 20px;
  font-size: 18px;
}

.stats-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 20px;
}

.stat-card {
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  display: flex;
  align-items: center;
  gap: 15px;
}

.stat-icon {
  width: 50px;
  height: 50px;
  border-radius: 8px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 24px;
}

.stat-content {
  flex: 1;
}

.stat-number {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 5px;
}

.stat-label {
  color: #909399;
  font-size: 14px;
}

.no-data {
  text-align: center;
  padding: 50px;
  /* 确保无数据时也能占位，防止布局跳动 */
  min-height: 200px;
  display: flex;
  align-items: center;
  justify-content: center;
  /* 如果放在 grid 容器内，需要设置 grid-column */
  grid-column: 1 / -1; /* 让无数据提示占满整个 grid 宽度 */
}

/* 响应式设计 */
@media (max-width: 768px) {
  .header {
    flex-direction: column;
    gap: 15px;
  }

  .controls {
    flex-wrap: wrap;
    justify-content: center; /* Controls centered when wrapped */
  }

  .popular-courses {
    grid-template-columns: 1fr;
  }

  .recommendations-grid {
    grid-template-columns: 1fr;
  }

  .stats-cards {
    grid-template-columns: repeat(2, 1fr);
  }
}

@media (max-width: 480px) {
  .stats-cards {
    grid-template-columns: 1fr;
  }
  .stat-card {
    flex-direction: column;
    text-align: center;
    gap: 10px;
  }
  .stat-icon {
    margin-bottom: 10px;
  }
}
</style>